﻿using HirelSeriesH.Global;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace HirelSeriesH.Entity
{
    public class PowerPack
    {
        public string PowerStepConfig;
        public List<Power> Powers = new List<Power>();
        public bool IsWork = false;
        private readonly object locker = new object();
        public bool NeedAutoEnd = false;
        public bool NeedPersonEnd = false;
        public Thread WorkThread = null;

        public List<Channel> ChannelList = new List<Channel>();

        public List<Channel> ChannelListPersonClose;

        public void StartWork()
        {
            if (IsWork)
            {
                return;
            }
            IsWork = true;
            NeedAutoEnd = false;
            NeedPersonEnd = false;

            lock (locker)
            {
                string[] StepStr = PowerStepConfig.Split('-');
                foreach (string step in StepStr)
                {
                    string[] StepConfigs = step.Split(';');
                    int PowerIndex = int.Parse(StepConfigs[1].Replace("DPS", "")) - 1;
                    Power power = Powers[PowerIndex];
                    if (!power.IsOpen)
                    {
                        power.setMaxCurrent();
                        System.Threading.Thread.Sleep(50);
                        power.setVolt(0);
                        System.Threading.Thread.Sleep(50);
                        power.open();
                        power.IsOpen = true;
                    }
                }

                while (true)
                {
                    if (NeedAutoEnd || NeedPersonEnd)
                    {
                        break;
                    }



                    if (ChannelList[0].TestParameter.isStatic)
                    {

                        foreach (string step in StepStr)
                        {
                            string[] StepConfigs = step.Split(';');

                            int stepNum = int.Parse(StepConfigs[0]);
                            int PowerIndex = int.Parse(StepConfigs[1].Replace("DPS", "")) - 1;
                            decimal StartVol = decimal.Parse(StepConfigs[2]);
                            decimal EndVolt = decimal.Parse(StepConfigs[3]);
                            decimal StepVolt = decimal.Parse(StepConfigs[4]);
                            double IntervalTime = double.Parse(StepConfigs[5]);
                            double DelayTime = double.Parse(StepConfigs[6]);

                            Power power = Powers[PowerIndex];

                            if (power.VoltageCurrent < EndVolt)
                            {

                                power.setVolt(StartVol);
                                power.VoltageCurrent = StartVol;


                                while (true)
                                {
                                    Thread.Sleep((int)(IntervalTime * 1000));
                                    if (StartVol <= EndVolt)//升压
                                    {
                                        if (power.VoltageCurrent + StepVolt < EndVolt)
                                        {
                                            power.setVolt(power.VoltageCurrent + StepVolt);
                                            power.VoltageCurrent = power.VoltageCurrent + StepVolt;
                                        }
                                        else
                                        {
                                            power.setVolt(EndVolt);
                                            power.VoltageCurrent = EndVolt;
                                            if (DelayTime > 0)
                                            {
                                                Thread.Sleep((int)(DelayTime * 1000));
                                                break;
                                            }
                                        }
                                    }

                                }
                            }



                        }
                    }
                    else
                    {

                        foreach (string step in StepStr)
                        {
                            string[] StepConfigs = step.Split(';');

                            int stepNum = int.Parse(StepConfigs[0]);
                            int PowerIndex = int.Parse(StepConfigs[1].Replace("DPS", "")) - 1;
                            decimal StartVol = decimal.Parse(StepConfigs[2]);
                            decimal EndVolt = decimal.Parse(StepConfigs[3]);
                            decimal StepVolt = decimal.Parse(StepConfigs[4]);
                            double IntervalTime = double.Parse(StepConfigs[5]);
                            double DelayTime = double.Parse(StepConfigs[6]);

                            Power power = Powers[PowerIndex];
                            power.setVolt(StartVol);
                            power.VoltageCurrent = StartVol;

                            while (true)
                            {
                                Thread.Sleep((int)(IntervalTime * 1000));
                                if (StartVol <= EndVolt)//升压
                                {
                                    if (power.VoltageCurrent + StepVolt < EndVolt)
                                    {
                                        power.setVolt(power.VoltageCurrent + StepVolt);
                                        power.VoltageCurrent = power.VoltageCurrent + StepVolt;
                                    }
                                    else
                                    {
                                        power.setVolt(EndVolt);
                                        power.VoltageCurrent = EndVolt;
                                        if (DelayTime > 0)
                                        {
                                            Thread.Sleep((int)(DelayTime * 1000));
                                            break;
                                        }
                                    }
                                }
                                else //降压
                                {
                                    if (power.VoltageCurrent - StepVolt > EndVolt)
                                    {
                                        power.setVolt(power.VoltageCurrent - StepVolt);
                                        power.VoltageCurrent = power.VoltageCurrent - StepVolt;
                                    }
                                    else
                                    {
                                        power.setVolt(EndVolt);
                                        power.VoltageCurrent = EndVolt;
                                        if (DelayTime > 0)
                                        {
                                            Thread.Sleep((int)(DelayTime * 1000));
                                            break;
                                        }
                                    }
                                }

                            }

                        }
                    }


                }

                IsWork = false;

                foreach (string step in StepStr)
                {
                    string[] StepConfigs = step.Split(';');
                    int PowerIndex = int.Parse(StepConfigs[1].Replace("DPS", "")) - 1;
                    Power power = Powers[PowerIndex];
                    if (power.IsOpen)
                    {
                        power.setVolt(0);
                        Thread.Sleep(50);
                        power.close();
                        power.IsOpen = false;
                    }
                }

                if (NeedPersonEnd)
                {
                    if (ChannelListPersonClose != null && ChannelListPersonClose.Count > 0)
                    {
                        foreach (var channel in ChannelListPersonClose)
                        {
                            channel.PauseTest();
                        }
                    }
                }

                //检查是否所有老化板程序都已结束
                int fg = 0;
                foreach (var channel in Global.Global.ChannelList)
                {
                    if (channel.State == "running")
                    {
                        fg = 1;
                        break;
                    }
                }
                if (fg != 1)
                {
                    if (Global.Global.PtcBox.IsOpen)
                    {
                        AutoRun.TimerCheckTemperature.Stop();
                        Thread.Sleep(1000);

                        //Global.Global.PtcBox.IsAtuoClose = false;
                        //关闭
                        string strCommand = "C1=OFF" + "\r\n";
                        Global.Global.BoxPort.Write(strCommand);

                        Thread.Sleep(1000);
                        AutoRun.TimerCheckTemperature.Start();

                        Global.Global.PtcBox.IsOpen = false;
                        Global.Global.ValueBoxRunning = false;
                    }

                    Debug.WriteLine("没有老化板在测试，则将指示灯设置为黄色。");
                    //没有老化板在测试，则将指示灯设置为黄色。
                    if (Global.Global.PlcPort != null && Global.Global.PlcPort.IsOpen)
                    {
                        ThreeColor.EequeueCommandQueue("Yellow");
                    }
                }
            }

        }

        public void StopWorkForAuto()
        {
            NeedAutoEnd = true;

            /*IsWork = false;

            if (WorkThread != null && WorkThread.IsAlive)
            {
                WorkThread.Abort();
            }
            WorkThread = null;

            string[] StepStr = PowerStepConfig.Split('-');
            foreach (string step in StepStr)
            {
                string[] StepConfigs = step.Split(';');
                int PowerIndex = int.Parse(StepConfigs[1].Replace("DPS", "")) - 1;
                Power power = Powers[PowerIndex];
                if (power.IsOpen)
                {
                    power.setVolt(0);
                    Thread.Sleep(50);
                    power.close();
                    power.IsOpen = false;
                }
            }*/
        }

        public void StopWorkForPerson()
        {
            NeedPersonEnd = true;

            /*IsWork = false;

            if (WorkThread != null && WorkThread.IsAlive)
            {
                WorkThread.Abort();
            }
            WorkThread = null;

            string[] StepStr = PowerStepConfig.Split('-');
            foreach (string step in StepStr)
            {
                string[] StepConfigs = step.Split(';');
                int PowerIndex = int.Parse(StepConfigs[1].Replace("DPS", "")) - 1;
                Power power = Powers[PowerIndex];
                if (power.IsOpen)
                {
                    power.setVolt(0);
                    Thread.Sleep(50);
                    power.close();
                    power.IsOpen = false;
                }
            }*/

        }

        public static List<string> getPowerStrByStep(string powerStep) {

            List<string> list = powerStep.Split(';')
                .Where(each => each.StartsWith("DPS"))
                .Distinct()
                .OrderBy(each =>
                {
                    if (char.IsDigit(each.Last()))
                    {
                        return int.Parse(each.Last().ToString());
                    }
                    return -1;
                }).ToList();

            return list;
        }

        public static void refreshGlobalPowerPackList() { 
            Dictionary<string ,PowerPack> newD = new Dictionary<string ,PowerPack>();

            foreach (var each in Global.Global.ChannelList) {
                if (each.TestParameter != null && each.PowerPack != null && each.PowerPack != new PowerPack()) {
                    string powerStr = string.Join(",", PowerPack.getPowerStrByStep(each.TestParameter.PowerStepConfig));

                    if (!newD.ContainsKey(powerStr)) {
                        newD.Add(powerStr, each.PowerPack);
                    }
                }
            }

            Global.Global.powerPackList = newD.ToDictionary(each => each.Key,each=>each.Value);
        }
    }
}
